package org.java.gateway.handle;

import org.java.gateway.Api.OAuthLogout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.logout.ServerLogoutHandler;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class OAuth2LogoutHandler implements ServerLogoutHandler {
    @Autowired
    private OAuthLogout oAuthLogout;

    @Override
    public Mono<Void> logout(WebFilterExchange exchange, Authentication authentication) {

        StringBuilder builder = new StringBuilder();
        exchange.getExchange().getRequest().getCookies().forEach((name, cookies) -> {
            cookies.forEach(cookie -> {
                builder.append(name)
                        .append("=")
                        .append(cookie.getValue())
                        // 分号后面有个空格，用于隔开多个Cookie的键值对
                        .append("; ");
            });
        });
        // 把结尾的分号去掉
        if (builder.length() > 2) {
            builder.delete(builder.length() - 2, builder.length());
        }

        String cookies = builder.toString();
        // 调用远程的方法完成远程退出登录
        oAuthLogout.logout(cookies);

        return Mono.empty();
    }
}
